﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CSharpTest.Net.Serialization;

namespace TEAA
{
    public class GenericPrimitiveSerializer<TKey> : ISerializer<TKey>
    {

        void ISerializer<TKey>.WriteTo(TKey value, Stream stream)
        {
            TypeCode typeCode = Type.GetTypeCode(typeof(TKey));

            switch (typeCode)
            {
                case TypeCode.Boolean:
                    PrimitiveSerializer.Boolean.WriteTo((bool)Convert.ChangeType(value, typeof(bool)), stream);
                    break;

                case TypeCode.Int32:
                    PrimitiveSerializer.Int32.WriteTo((int)Convert.ChangeType(value, typeof(int)), stream);
                    break;

                case TypeCode.Double:
                    PrimitiveSerializer.Double.WriteTo((double)Convert.ChangeType(value, typeof(double)), stream);
                    break;

                case TypeCode.Char:
                    PrimitiveSerializer.Char.WriteTo((char)Convert.ChangeType(value, typeof(char)), stream);
                    break;

                case TypeCode.String:
                    PrimitiveSerializer.String.WriteTo((string)Convert.ChangeType(value, typeof(string)), stream);
                    break;

                case TypeCode.DateTime:
                    PrimitiveSerializer.DateTime.WriteTo((DateTime)Convert.ChangeType(value, typeof(DateTime)), stream);
                    break;
            }

        }

        TKey ISerializer<TKey>.ReadFrom(Stream stream)
        {
            TypeCode typeCode = Type.GetTypeCode(typeof(TKey));

            switch (typeCode)
            {
                case TypeCode.Boolean:
                    return (TKey)Convert.ChangeType(PrimitiveSerializer.Boolean.ReadFrom(stream), typeof(TKey));

                case TypeCode.Int32:
                    return (TKey)Convert.ChangeType(PrimitiveSerializer.Int32.ReadFrom(stream), typeof(TKey));

                case TypeCode.Double:
                    return (TKey)Convert.ChangeType(PrimitiveSerializer.Double.ReadFrom(stream), typeof(TKey));

                case TypeCode.Char:
                    return (TKey)Convert.ChangeType(PrimitiveSerializer.Char.ReadFrom(stream), typeof(TKey));

                case TypeCode.String:
                    return (TKey)Convert.ChangeType(PrimitiveSerializer.String.ReadFrom(stream), typeof(TKey));

                case TypeCode.DateTime:
                    return (TKey)Convert.ChangeType(PrimitiveSerializer.DateTime.ReadFrom(stream), typeof(TKey));
            }


            return default(TKey);
        }

    }
}
